<template>
  <div class="content-box-full role-box">
    <ContainerBox>
      <template #header>
        <el-form
          @keyup.enter.native="handleSubmit"
          ref="formRef"
          :model="searchForm"
          label-width="auto"
          inline
          class="demo-ruleForm"
        >
          <el-form-item label="角色编号：" prop="workNo">
            <el-input v-model.number="searchForm.workNo" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="角色名称：" prop="username">
            <el-input v-model.number="searchForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <el-button
              v-permission="'sys:role:list'"
              type="primary"
              @click="handleSubmit('formRef')"
              >查询
            </el-button>
            <el-button v-permission="'sys:role:save'" @click="handleAdd" v-prevent-reclick
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </template>
      <template #default>
        <el-table
          :data="tableData"
          :empty-text="isLoadingTable ? '加载中...' : '暂无数据'"
          class="table-box"
          height="100%"
          stripe
          fit
          border
          highlight-current-row
        >
          <el-table-column label="角色编号" align="center" min-width="100" prop="roleId">
          </el-table-column>
          <el-table-column label="角色名称" align="center" min-width="100" prop="roleName">
          </el-table-column>
          <el-table-column label="备注" align="center" min-width="200" prop="remark">
          </el-table-column>
          <el-table-column label="创建时间" align="center" min-width="200" prop="createTime">
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="200">
            <template #default="{ row }">
              <el-button v-permission="'sys:role:update'" @click="editRoleInfo(row)"
                >编辑</el-button
              >
              <el-button
                v-permission="'sys:role:delete'"
                :disabled="row.roleName === '超级管理员'"
                @click="deleteRow(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <CommonPaging
          :total="tableTotal"
          @currentChange="handleCurrentChange"
          @sizeChange="handleSizeChange"
        ></CommonPaging>
      </template>
    </ContainerBox>
    <el-dialog
      lock-scroll
      top="10vh"
      class="common-el-dialog"
      v-model="addRoleDialog"
      :title="roleDialogType === 'add' ? '新增角色' : '编辑角色'"
      width="600"
      @close="handleClose"
    >
      <el-form ref="roleFormRef" :model="roleForm" :rules="roleRules" label-width="100px">
        <el-form-item label="角色名称:" prop="roleName">
          <!--          超级管理员 编辑时不可修改名称-->
          <el-input
            :disabled="roleDialogType !== 'add' && roleForm.roleName === '超级管理员'"
            v-model="roleForm.roleName"
            type="text"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="roleForm.remark" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="授权:">
          <el-tree
            node-key="menuId"
            ref="roleTreeRef"
            default-expand-all
            class="common-el-tree hx-scroll"
            :data="roleTree"
            :props="defaultProps"
            show-checkbox
          >
          </el-tree>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addRoleDialog = false">取消</el-button>
          <el-button type="primary" v-prevent-reclick @click="handleAddConfirm"> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import ContainerBox from '@/components/base/ContainerBox.vue'
import CommonPaging from '@/components/base/CommonPaging.vue'
import accessApi from '@/api/accessApi.js'
import message from '@/utils/elMessage.js'
import utils from '@/utils/utils.js'

onMounted(() => {
  //获取角色list
  fetchRoleList()
  //获取菜单权限list
  getMenuList()
})

const searchForm = ref({
  workNo: '',
  username: '',
})

//查询角色list
function handleSubmit() {
  handleCurrentChange(1)
}

const isLoadingTable = ref(false)
const tableData = ref([])
const tableTotal = ref(0)

function fetchRoleList() {
  isLoadingTable.value = true
  tableData.value = []
  tableTotal.value = 0
  const params = {
    t: Date.now(),
    page: pageNum.value,
    limit: pageSize.value,
    roleName: searchForm.value.username,
    id: searchForm.value.workNo,
  }
  accessApi
    .getRoleList(params)
    .then((res) => {
      if (res.code === 0) {
        tableData.value = res.page?.list || []
        tableTotal.value = res.page?.totalCount || 0
      } else {
        message.warning(res.message)
      }
    })
    .catch((error) => {
      console.error(error)
    })
    .finally(() => {
      isLoadingTable.value = false
    })
}

const pageSize = ref(10)
const pageNum = ref(1)

function handleCurrentChange(current) {
  pageNum.value = current
  fetchRoleList()
}

function handleSizeChange(size) {
  pageSize.value = size
  pageNum.value = 1
  fetchRoleList()
}

//新增弹窗
const roleDialogType = ref('add')
const addRoleDialog = ref(false)
const roleFormRef = ref(null)
const roleTreeRef = ref(null)
const roleForm = ref({
  roleName: '',
  remark: '',
})
const roleRules = ref({
  roleName: [{ required: true, message: '角色名称不可以为空', trigger: 'blur' }],
})
const roleTree = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}

//编辑
//当前编辑行
const currentEditRow = ref(null)

function editRoleInfo(row) {
  if (row.roleId) {
    accessApi.editRoleInfo(row.roleId).then((res) => {
      if (res.code === 0) {
        const roleInfo = res.role || {}
        currentEditRow.value = roleInfo
        roleForm.value = {
          roleName: roleInfo.roleName || '',
          remark: roleInfo.remark || '',
        }
        roleDialogType.value = 'edit'
        addRoleDialog.value = true
        nextTick(() => {
          if (roleInfo.menuIdList) {
            roleTreeRef.value.setCheckedKeys(roleInfo.menuIdList || [])
          }
        })
      } else {
        message.warning(res.msg)
      }
    })
  }
}

function deleteRow(row) {
  if (row.roleId) {
    message.confirm('您是否确定要删除该角色信息?', '提示').then(() => {
      deleteRoleInfo([row.roleId])
    })
  }
}

//删除角色
function deleteRoleInfo(roleIdList) {
  accessApi
    .deleteRoleInfo(roleIdList)
    .then((res) => {
      if (res.code === 0) {
        message.success(res.msg)
        handleCurrentChange(1)
      } else {
        message.warning(res.msg)
      }
    })
    .catch((error) => {
      console.error(error.messages)
    })
}

//获取菜单权限树形
function getMenuList() {
  const params = {
    t: Date.now(),
    languageType: 'zh',
  }
  accessApi
    .getMenuList(params)
    .then((res) => {
      if (Array.isArray(res)) {
        roleTree.value = utils.arrayToTree(res, {
          idKey: 'menuId',
          parentKey: 'parentId',
        })
      } else {
        message.warning('获取角色树形数据失败')
      }
    })
    .catch((error) => {
      message.error(error.messages)
    })
}

//新增角色
function handleAdd() {
  roleDialogType.value = 'add'
  addRoleDialog.value = true
}

function handleClose() {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  if (roleTreeRef.value) {
    roleTreeRef.value.setCheckedKeys([])
  }
}

//保存 || 编辑
function handleAddConfirm() {
  roleFormRef.value.validate((bool) => {
    if (bool) {
      const params = {
        roleId: currentEditRow.value?.roleId || undefined,
        roleName: roleForm.value.roleName,
        remark: roleForm.value.remark,
        menuIdList: (roleTreeRef.value.getCheckedNodes(false, true) || []).map((el) => el.menuId),
      }
      const fetchApi =
        roleDialogType.value === 'add' ? accessApi.saveRoleInfo : accessApi.updateRoleInfo
      fetchApi(params).then((res) => {
        if (res.code === 0) {
          addRoleDialog.value = false
          if (roleDialogType.value === 'add') {
            //请求第一页数据
            handleCurrentChange(1)
          } else {
            currentEditRow.value = null
            fetchRoleList()
          }
        } else {
          message.warning(res.msg)
        }
      })
    }
  })
}
</script>

<style scoped lang="scss">
.role-box {
}
</style>
